<script setup>
import Header from "@/components/header/Header.vue";
import Detail from "./components/Detail.vue";
import Type from "./components/Type.vue";
import QRBanner from "./components/QRBanner.vue";
import { computed, ref, onMounted } from "vue";
import {
  showConfirmDialog,
  showToast,
  showLoadingToast,
  closeToast,
} from "vant";
import { useRoute, useRouter } from "vue-router";
import api from "@/api/index.js";
import pay from "@/utils/pay.js";
import BookingPolicy from "@/components/booking-policy/BookingPolicy.vue";
import { formatTime } from "@/utils/time.js";

const fileUrl = import.meta.env.VITE_FILE_URL;

// 真实的 订单状态：0-待付款 1-待发货/待核销/待制作 2-待收货  3-已完成/已核销  4-退款中  5-已退款  6-已取消  7-已发货 8-主动退款
const route = useRoute();
const router = useRouter();
const couponInfo = ref([]);

const type = route.query.type;

const data = ref({});
const loading = ref(false);
const name = ref("");
const _getOrderInfo = () => {
  loading.value = true;
  api
    .getCardOrderInfo({
      orderNo: route.params.id,
    })
    .then((res) => {
      data.value = res.data;
      getCouponCardInfo(res.data?.cardId);
    })
    .finally(() => {
      loading.value = false;
    });
};

_getOrderInfo();

const beforeClose = (action) => {
  if (action === "cancel") {
    return true;
  }
  return new Promise((resolve) => {
    api
      .getCancelOrder({ orderNo: data.value.orderNo })
      .then(() => {
        _getOrderInfo();
        resolve(true);
      })
      .catch(() => {
        resolve(false);
      });
  });
};
const handeldelorder = () => {
  showConfirmDialog({
    message: "确定取消该订单?",
    beforeClose,
  });
};

// 继续支付
// pay.getPayld({ orderNumber: res.data })
function handelnewpay(id) {
  if (type === "scenic") {
    pay.getPayld({ orderNumber: id, type: "mini" });
  } else if (type === "hotel") {
    pay.getPayld({ orderNumber: id, type: "hotel" });
  } else if (type === "hotPot") {
    // pay.getPayld({ orderNumber: id, type: 'hotel' })
  }
  pay.getPayld({ orderNumber: id, type: "hotel" });
}

const refundClick = () => {
  if (data.value.spuListVos[0].refundType === "0") {
    showToast("该订单不可退款");
    return;
  }
  router.push({
    path: `/scenic/refund/${route.params.id}`,
    query: { type },
  });
};

const goScenicDetailClick = () => {
  if (type === "scenic") {
    router.push(`/scenicspot/${data.value.shopId}`);
  }
  if (type === "hotel") {
    router.push(`/hotel-detail/${data.value.scenicSpotEntity.id}`);
  }
  if (type === "hotPot") {
    router.push(`/hotpot/${data.value.scenicSpotEntity.id}`);
  }
};

const useQR = () => {
  const activeNames = ref(["1"]);
  const isShowQR = ref(false);
  const openQRClick = () => {
    isShowQR.value = !isShowQR.value;
    if (isShowQR.value) {
      activeNames.value = [];
    } else {
      activeNames.value = ["1"];
    }
  };
  return {
    activeNames,
    isShowQR,
    openQRClick,
  };
};

const { activeNames, isShowQR, openQRClick } = useQR();

const useBookingPolicyPopup = () => {
  const popupShow = ref(false);
  const bookingInstructionsClick = () => {
    popupShow.value = true;
  };

  const bookingPolicyClose = () => {
    popupShow.value = false;
  };

  return { popupShow, bookingInstructionsClick, bookingPolicyClose };
};

const { popupShow, bookingInstructionsClick, bookingPolicyClose } =
  useBookingPolicyPopup();

const showButton = computed(() => {
  if (type === "scenic" || type === "hotel") {
    return [0, 1, 4].includes(data.value?.status);
  }
  return false;
});
const getCouponCardInfo = (val) => {
  api.getCouponCardList({ cardId: val }).then((res) => {
    couponInfo.value = res.data;
  });
};

const revokeRefundClick = () => {
  showLoadingToast({
    message: "撤销中...",
    forbidClick: true,
    duration: 0,
  });
  let getCancelRefund;
  if (type === "scenic") {
    getCancelRefund = api.getScenicCancelRefund;
  } else {
    getCancelRefund = api.getHotelCancelRefund;
  }
  getCancelRefund({ refundNumber: data.value.refundNumber }).then((res) => {
    if (res.code === "200") {
      closeToast();
      _getOrderInfo();
      showToast("操作成功");
    }
  });
};
</script>

<template>
  <div class="order_detail">
    <Header title="订单详情" :back="true" />
    <div class="content" :class="{ content_bottom: showButton }">
      <Type :loading="loading" :data="data" :type="type" />
      <div class="card" :data="data">
        <div class="card_content">
          <template v-if="!loading">
            <div class="card_content_top" @click="goScenicDetailClick">
              <div class="content_right">
                <div class="top">
                  <div class="name">
                    {{ data.cardName }}
                  </div>
                  <div class="price">
                    <span class="icon text-orange">￥</span>
                    <span class="number text-orange">{{
                      data?.orderAmount
                    }}</span>
                  </div>
                </div>
                <div class="bottom">
                  <template v-if="type === 'panda' || type === 'haishua'">
                    <div class="bottom_list">
                      {{
                        data.remainTimes === -99
                          ? "无限次"
                          : `剩余次数：${data.remainTimes || "--"}`
                      }}
                    </div>
                    <div class="bottom_list bottom_list_open">
                      <div>
                        {{
                          data.isExpire == 1
                            ? "已过期"
                            : `有效期至：${data.expireTime}`
                        }}
                      </div>
                      <!-- <div
                        v-if="data?.status === 1"
                        class="open"
                        @click.stop="openQRClick"
                      >
                        {{ isShowQR ? "展开" : "收起" }}
                        <van-icon v-if="isShowQR" name="arrow-down" />
                        <van-icon v-else name="arrow-up" />
                      </div> -->
                    </div>
                  </template>
                  <template v-if="type === 'hotel'">
                    <div
                      class="bottom_list"
                      v-if="data?.useTime"
                      :class="{
                        expiring_soon: formatTime(data.useTime).isExpiringSoon,
                      }"
                    >
                      {{ formatTime(data.useTime, "有效期至").name }}
                    </div>
                    <div class="bottom_list bottom_list_open">
                      <div @click.stop="bookingInstructionsClick">
                        <template v-if="data.reservationGuidelines?.length">
                          <span class="booking_instructions">使用须知</span>
                          <van-icon name="arrow" />
                        </template>
                      </div>
                      <div
                        v-if="data?.status === 1"
                        class="open"
                        @click.stop="openQRClick"
                      >
                        {{ isShowQR ? "展开" : "收起" }}
                        <van-icon v-if="isShowQR" name="arrow-down" />
                        <van-icon v-else name="arrow-up" />
                      </div>
                    </div>
                  </template>
                  <template v-if="type === 'hotPot'">
                    <div class="bottom_list" v-if="data?.useTime">
                      有效期至: {{ data.useTime }}
                    </div>
                    <div class="bottom_list bottom_list_open">
                      <div
                        @click.stop="bookingInstructionsClick"
                        v-if="
                          data.reservationGuidelines?.length ||
                          data.spuListVos[0].productDetail
                        "
                      >
                        <span class="booking_instructions">使用须知</span>
                        <van-icon name="arrow" />
                      </div>
                      <div
                        v-if="data?.status === 1"
                        class="open"
                        @click.stop="openQRClick"
                      >
                        {{ isShowQR ? "展开" : "收起" }}
                        <van-icon v-if="isShowQR" name="arrow-down" />
                        <van-icon v-else name="arrow-up" />
                      </div>
                    </div>
                  </template>
                </div>
              </div>
              <van-image
                class="van_image"
                width="8rem"
                height="8rem"
                fit="cover"
                :src="data.coverImage"
              />
            </div>
            <!-- <van-collapse v-model="activeNames" :border="false">
              <van-collapse-item name="1" :is-link="false">
                <template #title></template>
                <QRBanner
                  :data="data"
                  v-if="data?.status === 1 && data.orderTicketListVos.length"
                  class="qr_banner_components"
                />
              </van-collapse-item>
            </van-collapse> -->
          </template>
          <van-skeleton v-else>
            <template #template>
              <div :style="{ display: 'flex', width: '100%' }">
                <van-skeleton-image />
                <div :style="{ flex: 1, marginLeft: '16px' }">
                  <van-skeleton-paragraph row-width="60%" />
                  <van-skeleton-paragraph />
                  <van-skeleton-paragraph />
                  <van-skeleton-paragraph />
                </div>
              </div>
            </template>
          </van-skeleton>
        </div>
        <Detail :data="data" :loading="loading" />
      </div>
      <div class="card-coupon mb10" v-if="couponInfo.length">
        <div class="coupon-item" v-for="item in couponInfo" :key="item.id">
          <div class="money">
            {{ item.discount }}<span class="fz22">折</span>
          </div>
          <div class="des">
            <div class="content">
              <p class="text-orange fz22 blod">{{ item.couponName }}</p>
              <p class="fz12">{{ item.couponDesc }}</p>
            </div>
          </div>
        </div>
      </div>
      <div
        v-if="data.cardType === 0"
        @click="
          () => {
            if (data?.isActivate == 0)
              router.push({
                path: '/goldenCard/activation',
                query: {
                  activateCode: data?.activateCode || '',
                },
              });
          }
        "
        :disabled="data?.isActivate == 1"
        :class="data?.isActivate == 1 ? 'btn-disabled' : 'btn'"
      >
        {{ data?.isActivate == 1 ? "已激活" : "立即激活" }}
      </div>
      <!-- <div
        v-if="data.cardType === 1"
        class="btn"
        @click="() => router.push('/my-card')"
      >
        查看卡券
      </div> -->
    </div>
    <!--    详情页 0-待支付 1-待使用/待发货 2-待收货 3-已完成 4-退款中 5-已退款 6-已取消-->

    <div v-if="showButton" class="bottom_button">
      <div
        @click="handelnewpay(data.orderNo)"
        v-if="data?.orderStatus === 0"
        class="button primary"
      >
        继续支付 ¥{{ data?.orderAmount }}
      </div>
      <div
        @click.stop="handeldelorder(data.orderNo)"
        v-if="data?.orderStatus === 0"
        class="button default"
      >
        取消订单
      </div>
    </div>

    <van-popup
      teleport="body"
      v-model:show="popupShow"
      round
      position="bottom"
      :style="{ 'max-height': '70vh' }"
    >
      <BookingPolicy
        :ticketsDetailsVoList="data.reservationGuidelines"
        :refundType="data.spuListVos[0].refundType"
        :isShowBook="false"
        :productDetail="data.spuListVos[0].productDetail"
        @bookingPolicyClose="bookingPolicyClose"
      />
    </van-popup>
  </div>
</template>

<style scoped lang="scss">
:deep(.van-cell) {
  padding: 0;
}
:deep(.van-skeleton) {
  padding: 0;
}
.order_detail {
  display: flex;
  flex-direction: column;
  height: 100%;
  //overflow-y: auto;

  .content {
    flex: 1;
    overflow-y: auto;
    background-color: #f9f8f3;
    .card {
      margin: 1rem 1.5rem;
      padding: 1.5rem;
      background: #fffffc;
      box-shadow: 0 1.2rem 2rem 0 rgba(2, 95, 38, 0.05);
      border-radius: 1rem;

      .card_content {
        background: #fffffc;
        border-bottom: 0.1rem solid #eeeeee;
        padding-bottom: 1.5rem;

        .card_content_top {
          display: flex;
          justify-content: space-between;
          flex-direction: row-reverse;
          height: 8rem;

          img {
            height: 8rem;
            width: auto;
            border-radius: 0.5rem;
          }

          .content_right {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            margin-left: 1rem;

            .top {
              display: flex;
              justify-content: space-between;

              .name {
                font-size: 1.6rem;
                color: #333333;
                font-weight: bold;
                line-height: 1.9rem;
                word-break: break-all;
                overflow: hidden;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
              }

              .price {
                color: #333333;
                margin-left: 1rem;
                font-weight: bold;

                .icon {
                  font-size: 1.4rem;
                }

                .number {
                  font-size: 1.8rem;
                }
              }
            }

            .bottom {
              color: #999999;
              font-size: 1.2rem;

              .bottom_list {
                display: flex;
                align-items: center;
                height: 1.7rem;
                line-height: 1.7rem;
                .expiring_soon {
                  color: #ed6316;
                }
                .booking_instructions {
                  margin-right: 0.2rem;
                }
                .open {
                  color: var(--van-primary-color);
                }
              }
              .expiring_soon {
                color: #ed6316;
              }
              .bottom_list_open {
                justify-content: space-between;
              }
            }
          }
        }

        .qr_banner_components {
          margin-top: 2.6rem;
        }
      }
    }
  }
  .content_bottom {
    margin-bottom: 6rem;
  }

  .bottom_button {
    display: flex;
    flex-direction: row-reverse;
    height: 6rem;
    padding: 1rem 1rem 0 0;
    box-sizing: border-box;
    position: absolute;
    bottom: 0px;
    background: #ffffff;
    width: 100%;
    .button {
      margin-left: 0.5rem;
      height: 3.8rem;
      line-height: 3.8rem;
      text-align: center;
      padding: 0 3rem;
      background: rgba(0, 0, 0, 0.05);
      border-radius: 0.5rem;
      font-size: 1.6rem;
    }
    .button_disabled {
      opacity: 0.5;
    }

    .primary {
      background-color: var(--van-primary-color);
      color: #ffffff;
    }

    .primary:active {
      background: #4b947f;
    }

    .default {
      background: rgba(0, 0, 0, 0.05);
      color: #666666;
    }

    .default:active {
      background: rgb(215, 214, 214);
    }
  }
  .btn,
  .btn-disabled {
    width: 130px;
    height: 34px;
    margin: 3.5rem auto;
    font-size: 1.6rem;
    border-radius: 5px;
    background: rgba(79, 172, 145, 1);
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    color: #fff;
  }
  .btn-disabled {
    background: #b1b1b1;
  }
}
.card-coupon {
  overflow: hidden;
  background-color: #ffffff;
  border-radius: 1rem;
  padding: 1rem;
  margin: 1.5rem;
  box-shadow: 2px 2px 6px rgba(189, 189, 189, 0.7);
  p {
    line-height: 1.5;
  }
}
.title {
  position: relative;
  margin-top: 1rem;
  margin-left: 3rem;
  font-size: 1.4rem;
  font-weight: bold;
  &::before {
    position: absolute;
    content: "";
    left: -1rem;
    height: 1.5rem;
    width: 0.4rem;
    border-radius: 0.2rem;
    background: rgba(79, 172, 145, 1);
  }
}
.desc {
  padding: 2rem;
}
.coupon-item {
  display: flex;
  height: 7.2rem;
  margin-bottom: 1.5rem;
  background: url("../../assets/images/oneCard/coupon_bg.png") no-repeat;
  background-size: 100% 100%;
}
.money {
  width: 27%;
  text-align: center;
  font-size: 3.6rem;
  line-height: 2;
  font-weight: normal;
  color: #fff;
}
.content {
  width: 100%;
}
.des {
  display: flex;
  flex: 1;
  padding: 0 2rem;
  align-items: center;
  justify-content: space-between;
}
.price {
  font-size: 3.4rem;
  color: rgb(239, 119, 35);
}
</style>